<!--
@Descripttion 选择框
@version 1.0.0
@Author Bell
@Date 2021-11-16
@LastEditors Bell
@LastEditTime 2021-11-16
@property {Object}  options     默认值([])                               备选列表 期望格式:[{value: '', label: ''}]
@property {Object}  keys        默认值({value: 'value', label: 'label'}) 指定字段名称 期望格式:{value: 'value', label: 'label'}
@property {String}  width       默认值(200px)                            输入框宽度
@property {Boolean} disabled    默认值(false)                            是否失效
@property {String}  placeholder 默认值(请选择)                            默认占位文本
@example <JYSelect v-model="xxx" v-model:label="xxx" :options="selectList" />
 -->
<template>
  <el-select
    v-model="value"
    @change="changeVal"
    :clearable="true"
    :style="`width: ${width}`"
    :disabled="disabled"
    :placeholder="placeholder"
  >
    <el-option
      v-for="item in options"
      :key="item[keys.value]"
      :label="item[keys.label]"
      :value="item[keys.value]"
    >
    </el-option>
  </el-select>
</template>

<script lang="ts">
import { defineComponent, ref, watch } from 'vue'

export default defineComponent({
  name: 'jy-select',
  props: {
    modelValue: {
      required: true
    },
    label: {
      default: ''
    },
    // 备选列表 期望格式:[{value: '', label: ''}]
    options: {
      type: Array,
      default: () => []
    },
    // 指定字段名称 期望格式:{value: 'value', label: 'label'}
    keys: {
      type: Object,
      default() {
        return {
          value: 'value',
          label: 'label'
        }
      }
    },
    // 输入框宽度
    width: {
      type: String,
      default: '200px'
    },
    // 是否失效
    disabled: {
      type: Boolean,
      default: false
    },
    // 默认占位文本
    placeholder: {
      type: String,
      default: '请选择'
    }
  },
  emits: ['change', 'update:modelValue', 'update:label'],
  setup (props: any, context: any) {
    
    // 绑定控件的值
    const value: any = ref(props.modelValue)
    
    // 监听属性，给 value 赋值
    watch(() => props.modelValue, (newVal: string, oldVal: string) => {
      value.value = newVal
    })
    
    // 向父组件提交事件
    const changeVal = (value: string) => {
      let obj: any = {}
      obj = props.options.find((item: any) => {
        return item[props.keys.value] === value
      })
      // console.log(obj)
      context.emit('update:modelValue', value)
      context.emit('update:label', obj[props.keys.label])
      context.emit('change', value)
    }
    
    return {
      value,
      changeVal
    }
  }
})
</script>
